package com.buke66.taoduo.goods.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buke66.taoduo.common.utils.PageUtils;
import com.buke66.taoduo.common.utils.Query;

import com.buke66.taoduo.goods.dao.GoodsCategoryDao;
import com.buke66.taoduo.goods.entity.GoodsCategoryEntity;
import com.buke66.taoduo.goods.service.GoodsCategoryService;


@Service("goodsCategoryService")
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryDao, GoodsCategoryEntity> implements GoodsCategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsCategoryEntity> page = this.page(
                new Query<GoodsCategoryEntity>().getPage(params),
                new QueryWrapper<GoodsCategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<GoodsCategoryEntity> listWithTree() {

        // 1.查出所有分类
        List<GoodsCategoryEntity> goodsCategoryEntities = baseMapper.selectList(null);

        // 2.查询出所有一级分类
        return goodsCategoryEntities.stream().filter(e -> e.getParentCid() == 0)
                .peek(primaryClassification -> {
                    primaryClassification.setChildren(getChildren(primaryClassification, goodsCategoryEntities));
                    primaryClassification.setSort(Optional.ofNullable(primaryClassification.getSort()).orElse(0));
                })
                .sorted(Comparator.comparingInt(GoodsCategoryEntity::getSort))
                .collect(Collectors.toList());
    }



    /**
     * @description: 递归方法，找出parentNode的所有子节点
     *@param parentNode
     * @param allNodes
     * @return: java.util.List<com.buke66.taoduo.goods.entity.GoodsCategoryEntity>
     * @created: 2021/10/10 12:00
     **/
    private List<GoodsCategoryEntity> getChildren(GoodsCategoryEntity parentNode, List<GoodsCategoryEntity> allNodes) {
        return allNodes.stream().filter(e -> e.getParentCid().equals(parentNode.getCatId()))
                .peek(childNode ->  {
                    childNode.setChildren(getChildren(childNode, allNodes));
                    childNode.setSort(Optional.ofNullable(childNode.getSort()).orElse( 0));
                })
                .sorted(Comparator.comparingInt(GoodsCategoryEntity::getSort))
                .collect(Collectors.toList());
    }

    @Override
    public void removeCategoryByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方所引用
        baseMapper.deleteBatchIds(asList);
    }

}